package com.spzx.product.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.utils.ServletUtils;
import com.spzx.product.domain.ProductSpec;
import com.spzx.product.mapper.ProductSpecMapper;
import com.spzx.product.service.CategoryService;
import com.spzx.product.service.ProductSpecService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductSpecServiceImpl extends ServiceImpl<ProductSpecMapper, ProductSpec>
    implements ProductSpecService {
    @Resource
    CategoryService categoryService;
    @Override
    public Page<ProductSpec> listProductSpec(ProductSpec productSpec) {
        Integer pageNum = ServletUtils.getParameterToInt("pageNum", 1);
        Integer pageSize = ServletUtils.getParameterToInt("pageSize", 3);
        Page<ProductSpec> page = new Page<>(pageNum, pageSize);
        //查询分页列表数据
        List<ProductSpec> list = baseMapper.selectProductSpecPage(page,productSpec);
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductSpec selectSpecById(Long id) {
        ProductSpec spec = this.getById(id);
        if(spec!=null){
            spec.setCategoryIdList(categoryService.selectCategoryIdsByC3Id(spec.getCategoryId()));
        }
        return spec;
    }

    @Override
    public boolean checkSpecIsUnique(ProductSpec productSpec) {
        Long id = productSpec.getId()==null?-1L:productSpec.getId();

        String specName = productSpec.getSpecName();
        Long categoryId = productSpec.getCategoryId();
        ProductSpec selectProductSpec = this.getOne(Wrappers.lambdaQuery(ProductSpec.class)
                                                    .eq(ProductSpec::getCategoryId, categoryId)
                                                    .eq(ProductSpec::getSpecName, specName)
                                                    .last("limit 1"));
        //如果是新增，spec不为空：返回false
        //如果是更新，spec不为空，并且spec的id 不等于更新的id：返回false
        if(selectProductSpec!=null && id.longValue()!=selectProductSpec.getId().longValue()){
            return false;
        }
        return true;
    }
}